/*
 * @Description: 小数的精确运算
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2022-03-24 09:29:06
 * @LastEditTime: 2022-03-24 11:31:08
 * @FilePath: \cscec-pms-admin\src\utils\decimalCalculation.js
 */
/**
 * @description: add:小数精确加法,sub:小数精确减法,mul:小数精确乘法,div:小数精确除法
 * @param {Number}
 * @return {Number}
 */
Object.defineProperties(Number.prototype, {
  'add': {
    value: function (v) {
      try {
        if (!(typeof v === 'number')) return NaN
        const v1 = this.toString()
        const v2 = v.toString()
        const l1 = v1.split('.')[1]?.length || 0
        const l2 = v2.split('.')[1]?.length || 0
        const r = Math.max(l1, l2)
        if (l1 === r) {
          return (Number(v1.replace('.', '')) + Number(v2.replace('.', '')) * Math.pow(10, l1 - l2)) / Math.pow(10, r)
        } else {
          return (Number(v1.replace('.', '')) * Math.pow(10, l2 - l1) + Number(v2.replace('.', ''))) / Math.pow(10, r)
        }
      } catch (error) {
        console.error(error)
      }
    }
  },
  'sub': {
    value: function (v) {
      return this.add(-v)
    }
  },
  'mul': {
    value: function (v) {
      try {
        if (!(typeof v === 'number')) return NaN
        const v1 = this.toString()
        const v2 = v.toString()
        const l1 = v1.split('.')[1]?.length || 0
        const l2 = v2.split('.')[1]?.length || 0
        return Number(v1.replace('.', '')) * Number(v2.replace('.', '')) / Math.pow(10, l1 + l2)
      } catch (error) {
        console.error(error)
      }
    }
  },
  'div': {
    value: function (v) {
      try {
        if (!(typeof v === 'number')) return NaN
        const v1 = this.toString()
        const v2 = v.toString()
        const l1 = v1.split('.')[1]?.length || 0
        const l2 = v2.split('.')[1]?.length || 0
        return (Number(v1.replace('.', '')) / Number(v2.replace('.', '')) * Math.pow(10, l1 - l2))
      } catch (error) {
        console.error(error)
      }
    }
  }
})